import Portal from '@/utils/Dom/Portal';
import React, { useEffect, useState } from 'react';
import DrawerPopup from './DrawerPopup';
import { TPortalParams, YmDrawerProps } from './interface';

const YmDrawer: React.FC<YmDrawerProps> = (props) => {
  const {
    prefixCls = 'ym-drawer',
    destroyOnClose = false,
    forceRender,
    getContainer,
    open,
    afterClose,
  } = props;
  const [animatedVisible, setAnimatedVisible] = useState<boolean>(open);

  useEffect(() => {
    if (open) {
      setAnimatedVisible(true);
    }
  }, [open]);

  if (!forceRender && destroyOnClose && !animatedVisible) {
    return null;
  }

  return (
    <Portal
      forceRender={forceRender}
      visible={open}
      getContainer={getContainer}
    >
      {(portalParams: TPortalParams) => (
        <DrawerPopup
          {...props}
          destroyOnClose={destroyOnClose}
          prefixCls={prefixCls}
          afterClose={() => {
            afterClose?.();
            setAnimatedVisible(false);
          }}
          {...portalParams}
        />
      )}
    </Portal>
  );
};

export default YmDrawer;
